package com.attendance.www.hr.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.EmployeeRoleMapper;
import com.attendance.www.hr.dao.mapper.RoleMapper;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeExample;
import com.attendance.www.hr.entitys.EmployeeRole;
import com.attendance.www.hr.entitys.EmployeeRoleExample;
import com.attendance.www.hr.entitys.Role;
import com.attendance.www.hr.entitys.RoleExample;
import com.attendance.www.hr.enums.IsRoleEnum;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IEmployeeRoleExcelService;

@Service
public class EmployeeRoleExcelServiceImpl implements IEmployeeRoleExcelService {

	@Resource
	private EmployeeRoleMapper employeeRoleDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private RoleMapper RoleDao;

	private Map<String, Integer> addEmployeeRoleMap;

	private Map<String, Integer> addOldEmployeeRoleMap;

	private Map<String, Employee> employeeMap;

	private Map<String, Role> roleMap;

	private Map<Integer, Integer> isRoleByidMap;

	private Map<String, Integer> isRoleMap;

	/**
	 * 删除岗位相关信息
	 * 
	 * @return
	 */
	@Override
	public boolean delEmployeeRole() {
		return true;
	}

	@Override
	public List<String> importEmployeeRole(Workbook work, AttachmentBean attachmentBean) {
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(attachmentBean.getFromDate());// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
		Date ThruDate = calendar.getTime(); // 得到前一天的时间
		Date oldThruDate = null;
		if (attachmentBean.getType() == 3) {
			EmployeeRoleExample example = new EmployeeRoleExample();
			EmployeeRoleExample.Criteria criteria = example.createCriteria();
			criteria.andThruDateIsNull();
			EmployeeRole employeeRole = new EmployeeRole();
			employeeRole.setThruDate(ThruDate);
			employeeRoleDao.updateByExampleSelective(employeeRole, example);
		}
		isRoleByidMap = new HashMap<Integer, Integer>();
		isRoleMap = new HashMap<String, Integer>();
		addEmployeeRoleMap = new HashMap<String, Integer>();
		addOldEmployeeRoleMap = new HashMap<String, Integer>();
		employeeMap = new HashMap<String, Employee>();
		roleMap = new HashMap<String, Role>();
		List<String> successList = new ArrayList<String>();

		EmployeeRoleExample example = new EmployeeRoleExample();
		example.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull();
		example.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate())
				.andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate());
		if (attachmentBean.getType() != 3) {
			List<EmployeeRole> employeeRoleList = employeeRoleDao.selectByExample(example);
			for (EmployeeRole employeeRole : employeeRoleList) {
				addEmployeeRoleMap.put(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId(), -1);
				oldThruDate = employeeRole.getThruDate();
				if (employeeRole.getIsRole() == 1) {
					isRoleByidMap.put(employeeRole.getEmployeeId(), -1);
				}
			}
		}
		// 判断导入类型 1.覆盖 2.增量
		EmployeeExample employeeExample = new EmployeeExample();
		employeeExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull();
		employeeExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate())
				.andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate());
		List<Employee> employeeList = employeeDao.selectByExample(employeeExample);
		for (Employee employee : employeeList) {
			employeeMap.put(employee.getEmployeeNo(), employee);
			if (isRoleByidMap.containsKey(employee.getEmployeeId())) {
				isRoleMap.put(employee.getEmployeeNo(), -1);
			} else {
				isRoleMap.put(employee.getEmployeeNo(), 0);
			}
		}
		RoleExample roleExample = new RoleExample();
		roleExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull();
		roleExample.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate())
				.andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate());
		List<Role> roleList = RoleDao.selectByExample(roleExample);
		for (Role role : roleList) {
			roleMap.put(role.getRoleCode(), role);
		}

		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("1.4员工与岗位关系")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					EmployeeRole employeeRole = new EmployeeRole();// 创建岗位对象
					EmployeeRole oldEmployeeRole = new EmployeeRole();// 创建岗位对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						break;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						break;
					}
					if (oldThruDate != null) {
						if (oldThruDate.getTime() >= attachmentBean.getFromDate().getTime()) {
							employeeRole.setThruDate(oldThruDate);
						}
					}
					employeeRole.setFromDate(attachmentBean.getFromDate());
					// 判断第二列岗位编码的合法性
					if (attachmentBean.getType() == 1) {
						if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
							String roleNo = row.getCell(0).toString();
							if (roleMap.containsKey(roleNo)) {
								oldEmployeeRole.setRoleId(roleMap.get(roleNo).getRoleId());
							} else {
								str.append("原岗位编码不存在,");
							}
						} else {
							str.append("原岗位编码不能为空,");
						}
					}
					// 判断第一列员工编码的合法性
					if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
						String employeeNo = row.getCell(2).toString();
						if (row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							employeeNo = new BigDecimal(row.getCell(2).getNumericCellValue()).intValue()+"";
						}else{
							employeeNo = row.getCell(2).toString();
						}
						if (employeeMap.containsKey(employeeNo)) {
							oldEmployeeRole.setEmployeeId(employeeMap.get(employeeNo).getEmployeeId());
							employeeRole.setEmployeeId(employeeMap.get(employeeNo).getEmployeeId());
						} else {
							str.append("员工号不存在,");
						}
					} else {
						str.append("员工号不能为空,");
					}
					if (attachmentBean.getType() == 1) {
						String roleNo= null;
						String employeeNo = null;
						if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
							roleNo = row.getCell(0).toString();
						}
						if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
							if (row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
								employeeNo = new BigDecimal(row.getCell(2).getNumericCellValue()).intValue()+"";
							}else{
								employeeNo = row.getCell(2).toString();
							}
						}
						
						
						if (addOldEmployeeRoleMap.containsKey(employeeNo + "@&" + roleNo)) {
							str.append("与第" + addOldEmployeeRoleMap.get(employeeNo + "@&" + roleNo) + "行原员工岗位编码重复,");
						}
					}

					// 判断第二列岗位编码的合法性
					if (row.getCell(4) != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
						String roleNo = row.getCell(4).toString();
						if (roleMap.containsKey(roleNo)) {
							employeeRole.setRoleId(roleMap.get(roleNo).getRoleId());
						} else {
							str.append("岗位编码不存在,");
						}
					} else {
						str.append("岗位编码不能为空,");
					}
					// 判断第三列开始日期
					if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
						try {
							Integer isRole = IsRoleEnum.getName(row.getCell(6).toString());
							employeeRole.setIsRole(isRole);
						} catch (Exception e) {
							str.append("主岗位格式不正确,");
						}
					} else {
						str.append("主岗位不能为空,");
					}
					if (attachmentBean.getType() == 1) {
						if (addEmployeeRoleMap
								.containsKey(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId())) {
							if (addEmployeeRoleMap
									.get(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId()) > 0) {
								str.append("与第"
										+ addEmployeeRoleMap
												.get(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId())
										+ "行员工对应岗位编码重复,");
							}
						}
					} else {
						if (addEmployeeRoleMap
								.containsKey(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId())) {
							if (addEmployeeRoleMap
									.get(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId()) > 0) {
								str.append("与第"
										+ addEmployeeRoleMap
												.get(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId())
										+ "行员工对应岗位编码重复,");
							} else {
								str.append("员工对应岗位编码已存在,");
							}
						}
					}

					if (employeeRole.getIsRole() == 1) {
						String employeeNo=null;
						if (row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							employeeNo = new BigDecimal(row.getCell(2).getNumericCellValue()).intValue()+"";
						}else{
							employeeNo = row.getCell(2).toString();
						}
						if (attachmentBean.getType() == 1) {
							
							
							if (isRoleMap.containsKey(employeeNo)) {
								if (isRoleMap.get(employeeNo) > 0) {
									str.append("与第" + isRoleMap.get(row.getCell(2).toString()) + "行主岗位重复,");
								} else {
									isRoleMap.put(employeeNo, i + 1);
								}
							} else {
								isRoleMap.put(employeeNo, i + 1);
							}
						} else {
							if (isRoleMap.containsKey(employeeNo)) {
								if (isRoleMap.get(employeeNo) > 0) {
									str.append("与第" + isRoleMap.get(employeeNo) + "行主岗位重复,");
								} else if (isRoleMap.get(employeeNo) == 0) {
									if (employeeRole.getIsRole() == 1) {
										isRoleMap.put(employeeNo, i + 1);
									}
								} else {
									str.append("主岗位已存在,");
								}
							} else {
								isRoleMap.put(employeeNo, i + 1);
							}

						}
					}

					// 判断第三列开始日期
					if (row.getCell(7) != null && StringUtils.isNotBlank(row.getCell(7).toString())) {
						Date fromDate = new Date();
						try {
							fromDate = row.getCell(7).getDateCellValue();
						} catch (Exception e) {
							str.append("开始日期格式不正确,");
						}
						if (fromDate != null) {
							employeeRole.setFromDate(fromDate);
						} else {
							str.append("开始日期格式不正确,");
						}
					} else {
						str.append("开始日期不能为空,");
					}

					// 判断第四列结束日期
					if (row.getCell(8) != null && StringUtils.isNotBlank(row.getCell(8).toString())) {
						Date fromDate = new Date();
						try {
							fromDate = row.getCell(8).getDateCellValue();
						} catch (Exception e) {
							str.append("结束日期格式不正确,");
						}
						if (fromDate != null) {
							employeeRole.setThruDate(fromDate);
						} else {
							str.append("结束日期格式不正确,");
						}
					}
					if (employeeRole.getFromDate() != null && employeeRole.getThruDate() != null)
						if (employeeRole.getFromDate().getTime() > employeeRole.getThruDate().getTime()) {
							str.append("开始日期大于结束日期,");
						}
					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						// 判断导入类型 1.覆盖 2.增量
						if (attachmentBean.getType() == 1) {
							EmployeeRoleExample example2 = new EmployeeRoleExample();
							example2.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate()).andThruDateIsNull()
									.andEmployeeIdEqualTo(oldEmployeeRole.getEmployeeId())
									.andRoleIdEqualTo(oldEmployeeRole.getRoleId());
							example2.or().andFromDateLessThanOrEqualTo(attachmentBean.getFromDate())
									.andThruDateGreaterThanOrEqualTo(attachmentBean.getFromDate())
									.andEmployeeIdEqualTo(oldEmployeeRole.getEmployeeId())
									.andRoleIdEqualTo(oldEmployeeRole.getRoleId());
							employeeRoleDao.updateByExample(employeeRole, example2);
							String employeeNo=null;
							if (row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
								employeeNo = new BigDecimal(row.getCell(2).getNumericCellValue()).intValue()+"";
							}else{
								employeeNo = row.getCell(2).toString();
							}
							String success = str.toString() + "员工编码(" + employeeNo + ")与岗位编码("
									+ row.getCell(4).toString() + ")";
							successList.add(success);
						} else {
							employeeRoleDao.insertSelective(employeeRole);
						}
						addEmployeeRoleMap.put(employeeRole.getEmployeeId() + "@&" + employeeRole.getRoleId(), i + 1);
						String roleNo = row.getCell(4).toString();
						String employeeNo=null;
						if (row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							employeeNo = new BigDecimal(row.getCell(2).getNumericCellValue()).intValue()+"";
						}else{
							employeeNo = row.getCell(2).toString();
						}
						addOldEmployeeRoleMap.put(employeeNo + "@&" + roleNo, i + 1);

					} else {
						String errorStr = str.toString().substring(0, str.toString().length() - 1);
						errorMsgList.add(errorStr);
					}
				}

				List<EmployeeRole> employeeRoleList = employeeRoleDao.selectByExample(example);
				for (EmployeeRole employeeRole : employeeRoleList) {
					oldThruDate = employeeRole.getThruDate();
					if (employeeRole.getIsRole() == 1) {
						isRoleByidMap.put(employeeRole.getEmployeeId(), -1);
					}
				}
				for (Employee employee : employeeList) {
					if (isRoleByidMap.containsKey(employee.getEmployeeId())) {
						isRoleMap.put(employee.getEmployeeNo(), -1);
					} else {
						isRoleMap.put(employee.getEmployeeNo(), 0);
					}
				}
				/*for (String in : isRoleMap.keySet()) {
					// map.keySet()返回的是所有key的值

					Integer str = isRoleMap.get(in);// 得到每个key多对用value的值
					if (str == 0) {
						String errorStr = "员工编码(" + in + ")未设置主岗位!";
						errorMsgList.add(errorStr);
					}
				}*/

				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("9_00005", errorMsgList);
				}

				if (successList.size() > 0) {
					successList.add(0, "员工与岗位导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "员工与岗位导入完成");
				}
				return successList;
			}
		}
		throw new ResultFaultException("9_00015");
	}
}
